package cn.xuewei.pachong;
import cn.xuewei.pachong.util.DBUtil;
import cn.xuewei.pachong.qiniuyun.Qiniuyun;
import cn.xuewei.pojo.entity.Video;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.*;
public class BiliVideo {

    public static void main(String[] args) throws IOException {
        HashMap<String,List<Video>> videomaps = new HashMap<>();  //视频集合
        Map<String, VideoInfo> VBmaps = new HashMap<>();
        String str="";
        Scanner scanner = new Scanner(System.in);
       // 获取搜索的所有视频地址
        System.out.println("请输入想要搜索的内容:");
        str=scanner.next();
        Document connect = null;
        try {
            connect = Jsoup.connect("https://search.bilibili.com/all?keyword="+str).get();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //获取BDid值
        Elements elements = connect.select("a");
        for (Element element : elements) {
            String url = element.attr("href");
            String title = element.select("img").attr("alt");
            String imgurl = element.select("img").attr("src");
            String BVid = null;
            VideoInfo videoInfo = new VideoInfo();
            if (url.startsWith("//www.bilibili.com/video/BV")){
                String pattern = "^.*?BV|/$";
                BVid = url.replaceAll(pattern, "");
                videoInfo.setTitle(title);
                videoInfo.setVBid(BVid);
                if (imgurl != "") {
                    imgurl = "http:" + imgurl;
                    videoInfo.setImgurl(imgurl);
                    VBmaps.put(BVid,videoInfo);
                }
            }
        }
        System.out.println(VBmaps);
        //输入BV获取视频地址
        System.out.println("输入BVID:");
        String BV = scanner.next();
        System.out.println("输入分类（1.Java 2.Python 3.C/C++ 4.前端设计）:");
        int category = scanner.nextInt();
        System.out.println("是否付费（0.免费 1.付费）");
        int is_paid = scanner.nextInt();
        System.out.println("课程介绍:");
        String description = scanner.next();
        int boughtnum = 0;
        double price = 0;
        if(is_paid == 1) {
            System.out.println("输入价格:");
            price = scanner.nextDouble();
        }
        videomaps.put(BV,getCid(BV));
        //上传封面图
        String imgurl = upImg(VBmaps.get(BV).getImgurl(),BV);
        System.out.println(imgurl);
        System.out.println(VBmaps.get(BV).getTitle());
        try (Connection connection = DBUtil.getConnection()) {
            String insertSQL = "INSERT INTO paid_courses(bvid,coursename,paid,imgeurl,price,description,boughtnum,categoryid) " +
                    "VALUES(?,?,?,?,?,?,?,?)";
            PreparedStatement ps2 = connection.prepareStatement(insertSQL);
            ps2.setString(1,BV);
            ps2.setString(2,VBmaps.get(BV).getTitle());
            ps2.setInt(3,is_paid);
            ps2.setString(4,imgurl);
            ps2.setDouble(5,price);
            ps2.setString(6,description);
            ps2.setInt(7,boughtnum);
            ps2.setInt(8,category);
            ps2.executeUpdate();
        }catch (Exception e){
            System.out.println(e);
        }
        int i = 0;
        for (Map.Entry<String, List<Video>> entry : videomaps.entrySet()) {
            List<Video> videoList = entry.getValue();
            for (Video video : videoList) {

                i++;
                System.out.println("正在上传到云存储,进度"+ i +"...........");

               String vurl = upVideo(video.getBvid(),video.getCid(),video.getTitle(),VBmaps.get(video.getBvid()).getTitle());
                try (Connection connection = DBUtil.getConnection()) {
                    String insertSQL = "INSERT INTO video(bvid,title,url) " +
                            "VALUES(?,?,?)";
                    PreparedStatement ps2 = connection.prepareStatement(insertSQL);
                    ps2.setString(1,video.getBvid());
                    ps2.setString(2,video.getTitle());
                    ps2.setString(3,vurl);
                    ps2.executeUpdate();
                }catch (Exception e){
                    System.out.println(e);
                }
            }
        }
    }

    //获取cid值
    private static List<Video> getCid(String bvid) {
        List<Video> videoList = new ArrayList<>();
        String CidUrl = "https://api.bilibili.com/x/web-interface/view?bvid=" + bvid;
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(CidUrl);
            URLConnection urlConnection = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());
        JSONArray pages = jsonObject.getJSONObject("data").getJSONArray("pages");
        if (pages != null && pages.size() > 0) {
            for (int i = 0; i < pages.size(); i++) {
                JSONObject page = pages.getJSONObject(i);
                int cid = page.getIntValue("cid");
                String title = page.getString("part");
                Video video = new Video(cid, bvid, title);
                videoList.add(video);
            }
        }
        return videoList;
    }

    //获取视频地址
    private static String getVideoAdd(String bvid,int cid){
        //qn---清晰度   80高清1080p    64 720p
        String CidUrl = "https://api.bilibili.com/x/player/playurl?cid="+cid+"&fnver=0&qn=64&otype=json&bvid="+bvid+"&fnval=2&player=1";
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(CidUrl);
            URLConnection urlConnection = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        json.toString();
        Map maps = (Map) JSON.parse(String.valueOf(json));
        Object o = ((Map) maps.get("data")).get("durl");
        return (String) ((JSONObject) ((JSONArray) o).get(0)).get("url");

    }

    //上传视频到七牛云存储
    private static String upVideo(String bvid,int cid,String title,String FileName){
        String add = getVideoAdd(bvid,cid);
        System.out.println(add);
        InputStream inputStream = null;
        Qiniuyun qiniuyun = new Qiniuyun();
        String vurl = null;
        title = bvid+System.currentTimeMillis();
        try {
            URL url = new URL(add);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Referer", "https://www.bilibili.com/video/BV"+bvid); // 填需要爬取的bv号
            urlConnection.setRequestProperty("Sec-Fetch-Mode", "no-cors");
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36");
            urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            urlConnection.setConnectTimeout(10 * 1000);
            inputStream = urlConnection.getInputStream();
            vurl = qiniuyun.upFile(inputStream,title,bvid);

        } catch (UnsupportedEncodingException ex) {
            //ignore
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return vurl;
    }
    private static String upImg(String url,String filename) throws IOException {
        URL Burl = new URL(url);
        URLConnection urlConnection = Burl.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        Qiniuyun qiniuyun = new Qiniuyun();
        String vurl = qiniuyun.upFile(inputStream,filename,"img");
        return vurl;
    }
}

